﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows.Controls.Ribbon;
using SHomeWorkshop.LunarConcept.Controls;
using System.Xml;
using SHomeWorkshop.LunarConcept.Tools;
using SHomeWorkshop.LunarConcept.ModifingManager;
using System.Windows;
using SHomeWorkshop.LunarConcept.Widgets;

namespace SHomeWorkshop.LunarConcept.Commands
{
    /// <summary>
    /// 创建时间：2012年3月27日
    /// 创建者：  杨震宇
    /// 
    /// 主要用途：为当前所定的所有内容部件添加背景圆（椭圆）。
    /// </summary>
    public static class InsertBackgroundEllipseCommand
    {
        #region 构造方法=====================================================================================================

        /// <summary>
        /// [静态][构造方法]
        /// 
        /// ——此方法会初始化并向WPF系统注册一个RoutedUICommand。
        /// </summary>
        static InsertBackgroundEllipseCommand()//类型构造器
        {
            routedUICmd = new RoutedUICommand(
                "InsertBackgroundEllipseCommand",
                "InsertBackgroundEllipseCommand",
                typeof(InsertBackgroundEllipseCommand),//创建RoutedUICommand对象
                null);//本程序考虑支持“命令模式”因此，这些命令完全没有必要直接支持快捷键。

            cmdBinding.Command = routedUICmd;
            cmdBinding.CanExecute += new CanExecuteRoutedEventHandler(cmdBinding_CanExecute);
            cmdBinding.Executed += new ExecutedRoutedEventHandler(cmdBinding_Executed);
        }

        #endregion

        #region 字段与属性===================================================================================================

        private static CommandBinding cmdBinding = new CommandBinding();
        /// <summary>
        /// 用在主窗口CommandBindings集合中的命令绑定。
        /// 
        /// 它的Command是RoutedUICommand。
        /// ——因此，RoutedUICommand是否可以运行将由CmdBinding的CanExecute事件决定。
        /// ——而且，RoutedUICommand的执行也是通过CmdBinding的Execute事件来进行的。
        /// </summary>
        public static CommandBinding CmdBinding
        {
            get { return cmdBinding; }
        }

        private static RoutedUICommand routedUICmd;
        /// <summary>
        /// [只读静态属性]表示在WPF系统中注册的一个RoutedUICommand。
        /// ——必须和CommandBinding配合才能使用。
        ///     CommandBinding要添加到主窗口的CommandBindings集合中；
        ///     RoutedUICommand则要向WPF系统注册。
        ///     
        /// ★说明：使用静态属性是因为这样在Xaml代码中比较便于绑定。
        /// </summary>
        public static RoutedUICommand RoutedUICmd
        {
            get { return routedUICmd; }
        }

        #endregion

        #region 方法=========================================================================================================

        /// <summary>
        /// 判断命令是否可以执行。
        /// ——由于可以直接调用Execute()方法，因此，即使被禁用，也不是不能执行相关功能！！！
        /// </summary>
        static void cmdBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            //考虑到性能问题，全部取消此判断。反正执行时会判断。
            //if (Globals.MainWindow == null)
            //{
            //    e.CanExecute = false; return;
            //}

            //EditorManager manager = Globals.MainWindow.EditorManager;
            //if (manager == null)
            //{
            //    e.CanExecute = false; return;
            //}

            //PageEditor pe = manager.GetMainSelectedPageEditor();
            //if (pe == null)
            //{
            //    e.CanExecute = false;
            //    return;
            //}

            //List<Widget> selWidgets = pe.GetSelectedWidgetsList();
            //int contentWidgetsCount = 0;
            //foreach (Widget w in selWidgets)
            //{
            //    if (w is Widgets.ContentWidget) contentWidgetsCount++;
            //}

            //if (contentWidgetsCount <= 0)
            //{
            //    e.CanExecute = false;
            //    return;
            //}

            e.CanExecute = true;
            return;
        }

        /// <summary>
        /// 命令被触发时，会调用本事件处理器方法。
        /// ——本方法实际上是调用ExeCute()这个静态方法来实现特定功能。
        /// </summary>
        static void cmdBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            //Execute();//此命令不直接调用。
        }

        /// <summary>
        /// [公开静态方法]即使此命令处于禁用状态，也可以通过代码调用此方法来执行特定任务！！！
        /// 
        /// 当被绑定的命令被调用（触发）时，会引发cmdBinding_Executed事件。
        /// 在cmdBinding_Executed事件处理器方法中已添加了调用Execute()方法的代码。
        /// 
        /// ——因此，触发命令，就相当于调用此方法！！！
        /// </summary>
        public static string Execute(bool sameSize = false)
        {
            if (Globals.MainWindow == null) return "　　未找到Globals.MainWindow。";

            EditorManager manager = Globals.MainWindow.EditorManager;
            if (manager == null) return "　　未找到页面管理器。";

            PageEditor mainPageEditor = manager.GetMainSelectedPageEditor();
            if (mainPageEditor == null) return "　　未找到任何选定页面。";

            List<Widget> selWidgets = mainPageEditor.GetSelectedWidgetsList();
            int contentWidgetsCount = 0;
            foreach (Widget w in selWidgets)
            {
                if (w is Widgets.ContentWidget) contentWidgetsCount++;
            }

            if (contentWidgetsCount <= 0) return "　　此命令仅用于对内容部件（文本区、图片框、组）添加一个背景圆。";

            XmlNode widgetSetNode = mainPageEditor.WidgetSetNode;
            if (widgetSetNode == null) return "　　未找到当前页面的WidgetSet节点，无法添加圆。";

            double r = Math.Sqrt(2) / 2;

            ModifingInfo info = new ModifingInfo() { ModifingDescription = "添加内容部件背景圆" };
            mainPageEditor.MasterManager.GetSelectedPageEditorStatus(info);
            mainPageEditor.MasterManager.GetSelectedWidgetStatus_Old(info);
            ModifingItem<Action, ModifingInfo> mi = new ModifingItem<Action, ModifingInfo>(info);

            double maxWidth = 0; double maxHeight = 0;
            if (sameSize)
            {
                foreach (Widgets.Widget w in selWidgets)
                {
                    if (w is Widgets.ContentWidget)
                    {
                        Rect rect = w.RealRect;
                        if (rect.Width > maxWidth) maxWidth = rect.Width;
                        if (rect.Height > maxHeight) maxHeight = rect.Height;
                    }
                }
            }

            foreach (Widget w in selWidgets)
            {
                if (w is ContentWidget == false)
                {
                    w.IsSelected = false;
                    continue;
                }

                Rect srcRect = w.RealRect;
                Point center = new Point(srcRect.Left + srcRect.Width / 2, srcRect.Top + srcRect.Height / 2);
                double halfA, halfB;

                if (sameSize)
                {
                    halfA = (maxWidth / r / 2);
                    halfB = (maxHeight / r / 2);
                }
                else
                {
                    halfA = (srcRect.Width / r / 2);
                    halfB = (srcRect.Height / r / 2);
                }

                Point newTopLeft = new Point(center.X - 10 - halfA, center.Y - 10 - halfB);
                Point newBottomRight = new Point(center.X + 10 + halfA, center.Y + 10 + halfB);

                XmlNode newNode = widgetSetNode.AppendXmlAsChild(Properties.Resources.EllipseXml);
                Widgets.EllipseWidget ew = new Widgets.EllipseWidget(mainPageEditor);
                ew.XmlData = newNode;
                ew.NewID();
                ew.StartPoint = newTopLeft;
                ew.EndPoint = newBottomRight;

                //按默认值设置属性
                //ew.WidgetOpacity = manager.EllipseStyle.WidgetOpacity;
                //ew.WidgetForeColor = manager.EllipseStyle.WidgetForeColor;
                //ew.WidgetBackColor = manager.EllipseStyle.WidgetBackColor;
                //ew.WidgetLineColor = manager.EllipseStyle.WidgetLineColor;
                //ew.WidgetLineWidth = manager.EllipseStyle.WidgetLineWidth;
                //ew.LineDash = manager.EllipseStyle.LineDash;
                //ew.IsShadowVisible = manager.EllipseStyle.IsShadowVisible;

                Action actionAddEllipse = new Action(ActionType.WidgetAdded,
                    mainPageEditor.Id, ew.Id, null, ew.XmlData.OuterXml);

                mainPageEditor.AddWidget(ew);

                if (w.IsMainSelected)
                {
                    ew.IsMainSelected = true;
                    info.NewMainSelectedWidgetID = ew.Id;
                }
                else
                {
                    ew.IsSelected = true;
                }

                info.AddWidgetID_NewSelected(ew.Id);

                mi.AddAction(actionAddEllipse);

                w.IsSelected = false;
            }

            if (mainPageEditor.MasterManager != null)
            {
                mainPageEditor.MasterManager.RegisterModifingItem(mi);
            }

            return string.Empty;
        }

        #endregion
    }
}
